function constrainCode(cache) {
  let code = `<androidx.constraintlayout.widget.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"`;
  if (cache.attrs) {
    for (var i = 0; i < cache.attrs.length; i++) {
      var attr = cache.attrs[i];
      code += attr + "\n";
    }
  }
  code += `>`;

  if (cache.children && cache.children.length > 0) {
    addConstrain(cache);

    for (let i = 0; i < cache.children.length; i++) {
      let child = cache.children[i];
      code += exportXmlByType(child);
    }
  }

  code += `</androidx.constraintlayout.widget.ConstraintLayout>`;

  return code;
}

function addConstrain(cache) {
  let children = cache.children;
  console.log("children", children);

  children.sort(function (a, b) {
    return -(a.data.x - b.data.x);
  });

  for (let i = 0; i < children.length; i++) {
    let child = children[i];
    let childData = child.data;
    let relative = child.relative;
    attrs = [];

    if (relative.leftBro && relative.leftBro.length > 0) {
      relative.leftBro.sort(function (a, b) {
        return -(a.x + a.width - b.x - b.width);
      });

      let leftBro = relative.leftBro[0];
      attrs.push(
        `app:layout_constraintStart_toEndOf="@id/${leftBro.data.id}"\n`
      );
      attrs.push(
        `android:layout_marginLeft="${unit(
          leftBro.data.x + leftBro.data.width - childData.x
        )}"\n`
      );
    } else {
      attrs.push(`app:layout_constraintStart_toStartOf="parent"\n`);
      attrs.push(`android:layout_marginLeft="${unit(childData.x)}"\n`);
    }

    // if (childData.x + childData.width == cache.data.x + cache.data.width) {
    //   attrs.push(`android:layout_width="0dp"\n`);
    //   attrs.push(`app:layout_constraintEnd_toEndOf="parent"\n`);
    // }

    // top
    if (relative.topBro && relative.topBro.length > 0) {
      relative.topBro.sort(function (a, b) {
        return -(a.data.y + a.data.height - b.data.y - b.data.height);
      });

      let topBro = relative.topBro[0];
      attrs.push(
        `app:layout_constraintTop_toBottomOf="@id/${topBro.data.id}"\n`
      );
      attrs.push(
        `android:layout_marginTop="${unit(
          topBro.data.y + topBro.data.height - childData.y
        )}"\n`
      );
    } else {
      attrs.push(`app:layout_constraintTop_toTopOf="parent"\n`);
      attrs.push(`android:layout_marginTop="${unit(childData.y)}"\n`);
    }

    // if (childData.y + childData.height == cache.data.y + cache.data.height) {
    //   attrs.push(`android:layout_height="0dp"\n`);
    //   attrs.push(`app:layout_constraintBottom_toBottomOf="parent"\n`);
    // }

    child.attrs = attrs;
  }
}

function onlyOne(list) {
  return list && list.length == 1;
}
